package com.sunxu.ioc.container;

import com.sunxu.ioc.domain.ImportantUser;
import com.sunxu.ioc.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;

import java.util.Map;

/**
 * @author 孙许
 * @version 1.0
 * @date 2020/4/12 2:47 下午
 */
public class BeanFactoryAsIocContainerDemo {
    public static void main(String[] args) {
        // 创建BeanFactory容器
        DefaultListableBeanFactory beanFactory  = new DefaultListableBeanFactory();
        // 加载配置
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        String location = "classpath:META-INF/dependency-lookup-context.xml";
        int loadBeanDefinitionCount = reader.loadBeanDefinitions(location);
        System.out.println("bean定义加载数量：" + loadBeanDefinitionCount);
        // 依赖查找集合对象
        lookupByCollectionType(beanFactory);
        ImportantUser bean = beanFactory.getBean(ImportantUser.class);
        System.out.println(bean);
    }

    /**
     * 按照集合类型查找
     *
     * @param beanFactory
     */
    private static void lookupByCollectionType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> beansOfType = listableBeanFactory.getBeansOfType(User.class);
            System.out.println(beansOfType);
        }
    }
}
